package fons.model.query.fun;

import java.util.List;

import com.google.common.collect.Lists;

public class MapFun implements Function {
	private final ListFun list;
	private final Function mappingFunction;
	
	public MapFun() {
		this(null);
	}

	public MapFun (Function mappingFunction) {
		this(mappingFunction, null);
	}
	
	public MapFun (Function mappingFunction, ListFun list) {
		this.mappingFunction = mappingFunction;
		this.list = list;
	}
	
	@Override
	public Function apply(Function other) {
		if (mappingFunction == null)
			return new MapFun(other);
		else if (list == null) {
			return new MapFun(mappingFunction, (ListFun) other.apply());
		}
		
		throw new IllegalArgumentException("map can only be used on a single list!");
	}

	@Override
	public Function apply() {
		List<Function> newList = Lists.newArrayListWithExpectedSize(list.get().size());
		for (Function mapped: list.get()) {
			newList.add(mappingFunction.apply(
					mapped.apply())
					.apply());
		}
		return new ListFun(newList);
	}

}
